//
//  HMAD.m
//  HMAD
//
//  Created by hm on 2017/8/11.
//  Copyright © 2017年 hm. All rights reserved.
//

@interface HMSetting()

@property (nonatomic, strong) NSString *appId;

@property (nonatomic, strong) NSString *secretKey;

@end

@implementation HMSetting

static HMSetting *g_HMSetting = NULL;

+ (HMSetting *)sharedManager {
    if (!g_HMSetting) {
        g_HMSetting = [[HMSetting alloc] init];
    }
    return g_HMSetting;
}

- (NSString*)getAppId {
    return self.appId;
}

- (NSString*)getSecretKey {
    return self.secretKey;
}

- (void)requestSettingsWithAppId:(NSString*)appId secretKey:(NSString *)secretKey {
    self.appId = appId;
    self.secretKey = secretKey;
    
    NSArray *documents = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [documents[0] stringByAppendingPathComponent:@"settings.plist"];
    
    //网络请求settings
    //1.settings路径
    //1.创建会话对象
    NSURLSession *session = [NSURLSession sharedSession];
    //2.根据会话对象创建task
    NSURL *url = [NSURL URLWithString:SettingsURL];
    //3.创建可变的请求对象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //4.修改请求方法为POST
    request.HTTPMethod = @"POST";
    //5.请求头
    [request setValue:SDKVersion forHTTPHeaderField:@"sv"];
    
    NSString *original =[[[self.appId stringByAppendingString:[HMTools getIdfa]] stringByAppendingString:@"|"] stringByAppendingString:self.secretKey];
    NSString *ck =[HMTools md5:original];
    [request addValue:ck forHTTPHeaderField:@"checksum"];
    //NSLog(@"%@", request.allHTTPHeaderFields);
    //6.请求体
    NSString *adId =[HMTools getIdfa];
    NSString *postParams =[[NSString alloc] initWithFormat:@"h=%@&hid=%@",self.appId, [HMTools md5:adId]];
    
    NSData *postData = [postParams dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    [request setHTTPBody:postData];
    //7..根据会话对象创建一个Task(发送请求）
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data,NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (data == nil) {
            //加载本地
            NSData * storeData = [NSData dataWithContentsOfFile:path];
            if (storeData != nil) {
                //json
                NSDictionary *settings = [NSJSONSerialization JSONObjectWithData:storeData options:(NSJSONReadingOptions) kNilOptions error:nil];
                if (settings == nil) {
                    NSString *domain = @"NO_SETTINGS";
                    NSString *desc =  @"no settings,check your network or ids";
                    NSDictionary *userInfo = @{ NSLocalizedDescriptionKey : desc };
                    NSError *se = [NSError errorWithDomain:domain code:1007 userInfo:userInfo];
                    [HMSetting loadFail:se deleteSetting:YES];
                    return ;
                }
                //根据保存数据解析
                [[HMTask sharedManager] executeBySettings];
                return;
            }
            //本地也没有
            NSString *domain = @"HTTP_EXCEPTION";
            NSString *desc =  [@"http exception:" stringByAppendingString:error.description];
            NSDictionary *userInfo = @{ NSLocalizedDescriptionKey : desc };
            NSError *se = [NSError errorWithDomain:domain code:2002 userInfo:userInfo];
            [HMSetting loadFail:se deleteSetting:NO];
            return;
        }
        //8.解密数据
        NSString *key = [[[self.secretKey stringByAppendingString:@"|"] stringByAppendingString:[HMTools md5:adId]] stringByAppendingString:@"|9z1hf6p9"];
        NSString *md5 =[[HMTools md5:key] substringToIndex:8];
        NSData *result = [HMTools DESDecrypt:data WithKey:md5];
        //保存
        [result writeToFile:path atomically:YES];
        [[HMTask sharedManager] executeBySettings];
    }];
    //7.执行任务
    [dataTask resume];
}

+ (void)loadFail:(NSError *)error deleteSetting:(BOOL)delete {
    if (delete) {
        NSArray *documents = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *path = [documents[0] stringByAppendingPathComponent:@"settings.plist"];
        
        NSFileManager *fileMgr = [NSFileManager defaultManager];
        [fileMgr removeItemAtPath:path error:nil];
    }
}

@end
